<?php
/**
 * Specialized components that wrap facebook's user.
 * Allowing easy access to user id, name, education
 *
 * @author Ecky
 */
Yii::import('application.components.facebook.Facebook');

class UserFb {
    public static $fb;
    private function initFb() {
        self::$fb = new Facebook(array(
            'appId' => '234818646541140',
            'secret' => 'aa284e380bc813d60a031610f53ef345',
        ));
    }

    private $user = null;
    public function  __construct($user_id = null) {
        //return;
        if(!isset ($fb) || $fb === null) $this->initFb();
        if($user_id === null) $user_id = "me";

        try { $this->user = self::$fb->api("/$user_id?fields=id,name,education,link"); }
        catch(FacebookApiException $e) { $this->user = null; }
        
        //Redirect user if token needed
        if($this->user == null || isset($this->user['error'])) {
            $loginUrl = self::$fb->getLoginUrl(array(
                'req_perms' => 'user_education_history'
            ));
            echo '<script>top.location="'.$loginUrl.'";</script>';
            Yii::app()->end();
        }
    }

    public function getName() {
        //return 'dummy';
        return $this->user['name'];
    }

    public function getId() {
        //return '1231212';
        return $this->user['id'];
    }

    public function getLink() {
        //return 'http://www.facebook.com';
        return $this->user['link'];
    }

    public function isEducation($schoolnames) {
        return true;
        //early exit if education fields is not available
        if(!isset ($this->user['education'])) return false;

        foreach($this->user['education'] as $edu) {
            $curSchoolName = $edu['school']['name'];
            foreach($schoolnames as $schoolname) {
                if(strcasecmp(trim($schoolname), trim($curSchoolName)) == 0) return true;
            }
        }
        return false;
    }
}
?>
